import 'dart:async';
import 'dart:io';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/widgets/common_button.dart';
import 'package:intl/intl.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/domain/login/login_password_page.dart';
import 'package:flutter_syt/domain/login/widgets/login_account_form.dart';
import 'package:flutter_syt/domain/widgets/code_form_field.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/global_common.dart';
import 'package:flutter_syt/global_easy_loading.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/utils_other.dart';
import 'package:flutter_syt/widgets/dyt_aliyun_widget.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

import '/domain/login/widgets/login_protocol.dart';
import 'widgets/login_container.dart';
import 'widgets/login_input_decorator.dart';

@RoutePage(name: "loginByCode")
class LoginByCodePage extends StatefulWidget {
  const LoginByCodePage();

  @override
  _LoginByCodePageState createState() => _LoginByCodePageState();
}

class _LoginByCodePageState extends State<LoginByCodePage> {
  // late TabController _tabController;
  bool blurBackground = false;
  final _formKey = GlobalKey<FormState>();

  FocusNode phoneFocusNode = FocusNode();
  FocusNode codeFocusNode = FocusNode();

  // PhoneWithAreaCodeEntity _phone = PhoneWithAreaCodeEntity();

  String _account = '';

  String _code = '';

  bool _agree = false;

  @override
  void initState() {
    super.initState();
    // _tabController = TabController(length: 2, vsync: this);
    // phoneFocusNode.addListener(() {
    //   setState(() {
    //     blurBackground = phoneFocusNode.hasFocus;
    //   });
    // });
    // codeFocusNode.addListener(() {
    //   setState(() {
    //     blurBackground = codeFocusNode.hasFocus;
    //   });
    // });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        // 避免键盘弹起时高度错误
        resizeToAvoidBottomInset: false,
        body: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: ClickUtils.debounce(() {
              // 触摸收起键盘
              FocusScope.of(context).requestFocus(FocusNode());
            }),
            child: LoginContainer(
                // blurBackground: blurBackground,
                child: Form(
                    key: _formKey,
                    child: Container(
                      margin: EdgeInsets.symmetric(horizontal: 30),
                      child: Column(
                        children: [
                          Container(
                            alignment: Alignment.centerLeft,
                            margin: EdgeInsets.only(bottom: 20.w),
                            child: Text(
                              S().login_accountCode,
                              style: const TextStyle(
                                  color: Colors.black,
                                  fontSize: 20,
                                  fontWeight: FontWeight.w600),
                            ),
                          ),
                          BlurRectWidget(
                            LoginAccountForm(
                              focusNode: phoneFocusNode,
                              hintText: S().login_inputAccountCode,
                              onSaved: (newValue) {
                                _account = newValue ?? '';
                              },
                            ),
                            padding: 0,
                          ),
                          // BlurRectWidget(
                          //   LoginPhoneFormField(
                          //     focusNode: phoneFocusNode,
                          //     onSaved: (val) {
                          //       _phone = val!;
                          //     },
                          //   ),
                          // ),
                          SizedBox(
                            height: 24,
                          ),
                          BlurRectWidget(
                            CodeFormField(
                              tagStr: 'loginbycodeephone',
                              focusNode: codeFocusNode,
                              getSmsCode: getSmsCode,
                              decoration: LoginInputDecoration(),
                              onSaved: (val) {
                                _code = val!;
                              },
                            ),
                          ),

                          Container(
                            alignment: Alignment.centerLeft,
                            margin: const EdgeInsets.only(top: 4),
                            width: double.infinity,
                            // child: Theme(
                            //   // Create a unique theme with `ThemeData`
                            //   data: ThemeData(
                            //       splashColor: Colors.yellow,
                            //       textButtonTheme: TextButtonThemeData(
                            //         style: TextButton.styleFrom(
                            //           // primary: Colors.white,
                            //           padding:
                            //               EdgeInsets.symmetric(horizontal: 0),
                            //         ),
                            //       )),
                            //   child: TextButton(
                            //     child: Text(S.of(context).log_in_with_password,
                            //
                            //     ),
                            //     onPressed: ClickUtils.debounce(() {
                            //       Navigator.of(context).pop();
                            //     }),
                            //   ),
                            // ),
                            child: GestureDetector(
                              onTap: ClickUtils.debounce(() {
                                Navigator.of(context).pop();
                              }),
                              child: Text(
                                S.of(context).log_in_with_password,
                                style: const TextStyle(
                                  fontSize: 14,
                                  color: Colors.black87,
                                ),
                              ),
                            ),
                          ),
                          SizedBox(
                            height: 20,
                          ),
                          LoginProtocol(onChange: (value) {
                            setState(() {
                              _agree = value;
                            });
                          }),
                          Container(
                            margin: const EdgeInsets.only(top: 30, bottom: 16),
                            width: double.infinity,
                            // child: ElevatedButton(
                            //     child: Text(
                            //       S.of(context).log_in,
                            //       style: TextStyle(fontWeight: FontWeight.bold),
                            //     ),
                            //     onPressed: ClickUtils.debounce(
                            //       () {
                            //         _submit();
                            //       },
                            //     )),

                            child: CommonButton.expend(
                              title: S.of(context).log_in,
                              // height: 30,
                              onAsyncClick: () async {
                                await _submit();
                                // await Future.delayed(Duration(seconds: 2));
                              },
                            ),
                          ),
                          RichText(
                              text: TextSpan(
                                  style: TextStyle(
                                      fontSize: 14, color: Colors.black87),
                                  children: [
                                TextSpan(
                                  text: S().login_infoLeft,
                                ),
                                TextSpan(
                                  text: S().login_infoTap,
                                  recognizer: TapGestureRecognizer()
                                    ..onTap = () {
                                      RouteManager.push(
                                        context,
                                        RoutMapping.register(),
                                      );
                                    },
                                  style: const TextStyle(
                                      fontSize: 14,
                                      color: ThemeColor.primaryColor,
                                      fontWeight: FontWeight.bold,
                                      decorationColor: ThemeColor.primaryColor,
                                      decorationThickness: 2,
                                      // decorationStyle: TextDecorationStyle.double,
                                      decoration: TextDecoration.underline),
                                ),
                                TextSpan(
                                  text: S().login_infoRight,
                                  style: TextStyle(fontSize: 14),
                                ),
                              ])),
                        ],
                        // bottom: OtherAuthLogin(),
                      ),
                    )))));
  }

  Future<bool> getSmsCode() async {
    if (!_agree) {
      customShowToast(S.of(context).privacy_policy_consent_t);
      return false;
    }
    final form = _formKey.currentState;
    form!.save();
    // if (_phone.areaCode == '86') {
    //   if (!RegexUtil.isMobileSimple(_phone.phone)) {
    //     customShowToast(S.of(context).enter_valid_phone);
    //     return false;
    //   }
    // } else
    // if (!RegexUtil.matches('^\\d{6,25}\$', _account)) {
    //   customShowToast(S.of(context).enter_valid_account);
    //   return false;
    // }
    // if (_account.length < 6 || _account.length > 25) {
    //   customShowToast(S.of(context).enter_valid_account);
    //   return false;
    // }
    if (_account.length < 6 || _account.length > 60) {
      customShowToast(S.of(context).enter_valid_account);
      return false;
    }
    bool isVertifica = await UtilsOther.checkShowVertification(
        account: _account,
        context: context,
        status: DytAliyunStatus.DytAliyunStatusLogin);
    if (isVertifica == false) {
      return true;
    }

    try {
      bool res = await API.shared.login.accountCode(_account);
      // bool res = await API.shared.login
      //     .getPhoneCode(_phone.areaCode, _phone.phone, 'login');
      customShowToast(S().send_code_1);
      return true;
    } catch (e) {
      await UtilsOther.showCustomShowError(e);
      // if (e is DioError) {
      //   customShowError(e.message);
      // } else {
      //   customShowError(S().network_error);
      // }
      return true;
    }
  }

  Future _login() async {
    await API.shared.login.accountCodeLogin(
        _account,
        _code,
        (Platform.isIOS
            ? appContext.iOSInfo.identifierForVendor
            : appContext.andriodInfo.androidId));
    // await API.shared.login.phoneCodeLogin(_phone.areaCode, _phone.phone, _code);
    await API.shared.user.updateUserInfo('lang',
        appContext.storage.getString("storyLocal") ?? Intl.getCurrentLocale());
  }

  Future _submit() async {
    final form = _formKey.currentState;
    form?.save();
    // if (_phone.areaCode == '86') {
    //   if (!RegexUtil.isMobileSimple(_phone.phone)) {
    //     customShowToast(S.of(context).enter_valid_phone);
    //     return;
    //   }
    // } else
    // if (!RegexUtil.matches('^\\d{6,25}\$', _account)) {
    //   customShowToast(S.of(context).enter_valid_account);
    //   return;
    // }
    if (_account.length < 6 || _account.length > 60) {
      customShowToast(S.of(context).enter_valid_account);
      return;
    }
    if (!_agree) {
      customShowToast(S.of(context).privacy_policy_consent_t);
      return;
    }
    // final form = _formKey.currentState;
    if (form!.validate()) {
      try {
        await loading(_login, text: S.of(context).on_login);
        customShowToast(S.of(context).login_success);
        GlobalData.bindPush();
        GlobalData.getIndexSetting();
        Navigator.of(context).popUntil((route) {
          print('pageName: ${route.settings.name}, isFirst: ${route.isFirst}');
          if (GlobalData.pageFrom.isNotEmpty) {
            if (GlobalData.pageFrom == route.settings.name) {
              GlobalData.cleanPage();
              return true;
            } else {
              return false;
            }
          }
          return route.isFirst;
        });
      } catch (_) {}
      // Navigator.of(context).popUntil((route) {
      //   print('pageName: ${route.settings.name}, isFirst: ${route.isFirst}');
      //   return route.isFirst;
      // });
    }
  }
}
